package com.chinaoly.baotou.common.utils;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author xuyh
 * @date 2021/8/14
 */
@Component
public class RedisUtil {

    private static final String LOCK_SCRIPT = "if redis.call('setNX', KEYS[1], ARGV[1]) == 1 then return redis.call('expire', KEYS[1], ARGV[2]) else return 0 end";

    private static final String UNLOCK_SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 设置String缓存
     *
     * @param key
     * @param value
     */
    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 设置list缓存
     *
     * @param key
     * @param value
     * @param seconds 秒
     */
    public void set(String key, Object value, long seconds) {
        redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
    }

    /**
     * 写入缓存设置时效时间
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value, Long expireTime, TimeUnit timeUnit) {
        boolean result = false;
        try {
            ValueOperations<String, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, timeUnit);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * setNx
     *
     * @param key
     * @param value
     * @param seconds 过期时间：秒
     * @return
     */
    public boolean setNx(String key, Object value, long seconds) {
        // 通过lua脚本来保证操作的原子性
        DefaultRedisScript<Long> script = new DefaultRedisScript<>();
        script.setScriptText(LOCK_SCRIPT);
        script.setResultType(Long.class);
        Long result = redisTemplate.execute(script, Collections.singletonList(key), value, seconds);
        return new Long(1).equals(result);
    }

    /**
     * 加
     *
     * @param key
     * @param count
     */
    public void increment(String key, long count) {
        redisTemplate.opsForValue().increment(key, count);
    }

    /**
     * 获取缓存
     *
     * @param key
     * @return
     */
    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * hashSet
     *
     * @param key
     * @param field
     * @param value
     */
    public void hSet(String key, String field, Object value) {
        hSet(key, field, value, 0);
    }

    /**
     * hash
     *
     * @param key
     * @param field
     * @param value
     * @param seconds
     */
    public void hSet(String key, String field, Object value, long seconds) {
        redisTemplate.opsForHash().put(key, field, value);
        if (seconds > 0) {
            this.expire(key, seconds);
        }
    }

    /**
     * hash
     *
     * @param key
     * @param map
     */
    public void hSet(String key, Map<String, Object> map) {
        hSet(key, map, 0);
    }

    /**
     * hash
     *
     * @param key
     * @param map
     * @param seconds
     */
    public void hSet(String key, Map<String, Object> map, long seconds) {
        redisTemplate.opsForHash().putAll(key, map);
        if (seconds > 0) {
            this.expire(key, seconds);
        }
    }

    /**
     * 获取hash
     *
     * @param key
     * @param field
     * @return
     */
    public Object hGet(String key, String field) {
        return redisTemplate.opsForHash().get(key, field);
    }

    /**
     * 获取hash
     *
     * @param key
     * @return
     */
    public Map<Object, Object> hGet(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * 设置set类型
     *
     * @param key
     * @param values
     */
    public void sSet(String key, Object... values) {
        redisTemplate.opsForSet().add(key, values);
    }

    /**
     * 获取set类型
     *
     * @param key
     * @return
     */
    public Set<Object> sGet(String key) {
        return redisTemplate.opsForSet().members(key);
    }

    /**
     * 模糊匹配key
     *
     * @param key
     * @return
     */
    public Set<String> keys(String key) {
        return redisTemplate.keys(key);
    }

    /**
     * 设置失效时间
     *
     * @param key
     * @param time 秒
     */
    public void expire(String key, long time) {
        redisTemplate.expire(key, time, TimeUnit.SECONDS);
    }

    /**
     * 获取失效时间
     *
     * @param key 秒
     */
    public Long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 是否存在缓存
     *
     * @param key
     * @return ture-是，false-否
     */
    public boolean hasKey(String key) {
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }

    /**
     * 删除缓存
     *
     * @param key
     * @return
     */
    public boolean del(String key) {
        return Boolean.TRUE.equals(redisTemplate.delete(key));
    }

    /**
     * 锁
     *
     * @param key   锁名称
     * @param value 锁唯一标识
     * @param time  过期时间：秒
     * @return
     */
    public boolean lock(String key, String value, long time) {
        // 通过lua脚本来保证操作的原子性
        DefaultRedisScript<Long> lockScript = new DefaultRedisScript<>();
        lockScript.setScriptText(LOCK_SCRIPT);
        lockScript.setResultType(Long.class);
        Long result = redisTemplate.execute(lockScript, Collections.singletonList(key), value, time);
        return new Long(1).equals(result);
    }

    /**
     * 释放锁
     *
     * @param key
     */
    public void unlock(String key, String value) {
        // 通过lua脚本来保证操作的原子性
        DefaultRedisScript<Integer> lockScript = new DefaultRedisScript<>();
        lockScript.setScriptText(UNLOCK_SCRIPT);
        lockScript.setResultType(Integer.class);
        redisTemplate.execute(lockScript, Collections.singletonList(key), value);
    }

}
